package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/astaxie/beego/validation"
	"go-pipe/api/utilsfile/errmsg"
	"go-pipe/api/model"
	"net/http"
	"go-pipe/api/utilsfile/settings"
	"go-pipe/api/utilsfile/logging"
)

type auth struct {
	Username string `vaild:"Required;MaxSize(50)"`
	Password string `vaild:"Required;MaxSize(50)"`
}

// @Summary 用户校验
// @Produce  json
// @Param name query string true "Name"
// @Param state query int false "State"
// @Param created_by query int false "CreatedBy"
// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
// @Router /auth [post]

func GetAuth(c *gin.Context) {

	username := c.Query("username")
	password := c.Query("password")

	valid := validation.Validation{}

	valid.Required(username, "username").Message("名称不能为空")
	valid.Required(password, "password").Message("名称不能为空")

	data := make(map[string]interface{})

	code := errmsg.INVALID_PARAMS

	if !valid.HasErrors() {
		isExist := model.CheckAuth(username, password)

		if isExist {
			if token, err := settings.GenerateToken(username, password); err == nil {
				data["token"] = token
				code = errmsg.SUCCESS
			} else {
				code = errmsg.ERROR_AUTH_TOKEN
			}

		} else {
			code = errmsg.ERROR_AUTH
		}
	} else {
		for _, err := range valid.Errors {
			logging.Info("auth", "400", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  errmsg.GetMsg(code),
		"data": data,
	})
}
